package com.sz.app.oss.api.common.customer;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.common.customer.dto.CusCustomerDto;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.utils.StringUtils;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xutao on 17/4/7.
 */
@RestController
@RequestMapping("${api}/customer")
@Api(description = " ", tags = "037-001、客户信息管理-主账号")
public class CusCustomerController extends BaseController {

    @Autowired
    CustomerService customerService;

    @Autowired
    CustomerUserService customerUserService;

    /**
     * 获取客户列表
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "搜索客户", notes = "搜索用户，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字,账户名称或公司名称",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "beyondLeval", value = "级别以上",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "advancedSeach", value = "高级搜索",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "refCombos", value = "套餐编码",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isLocked", value = "锁定状态，0未锁定，1锁定",
                    dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "evaluateLeval", value = "评价等级",
                    dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "客户类型：1是物流，2是贸易， 3两者都是",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public QResultDto getCustomer(@RequestParam(defaultValue = "") String q,
                                  @RequestParam(required = true, defaultValue = "false") boolean beyondLeval,
                                  @RequestParam(required = true, defaultValue = "false") boolean advancedSeach,
                                  @RequestParam(required = false,defaultValue = "createTime") String sortName,
                                  @RequestParam(required = false, defaultValue = "false") boolean isAsc,
                                  @RequestParam(defaultValue = "1") int pageIndex,
                                  @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                  @RequestParam(defaultValue = "") String refCombos,
                                  @RequestParam(defaultValue = "-1") Integer isLocked,
                                  @RequestParam(defaultValue = "0") Integer evaluateLeval,
                                  @RequestParam(name = "userType", defaultValue = "1") int userType)
            throws BizException {

        q = StringUtils.replaceSqlPattern(q);

        return customerService.find(q, sortName, isAsc, pageIndex, pageSize, refCombos, isLocked,
                evaluateLeval, beyondLeval, advancedSeach, userType);
    }


    /**
     * 获取客户列表,返回id， userName, code
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "搜索客户", notes = "搜索用户，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字,账户名称或code",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "客户类型：1是物流，2是贸易， 3两者都是",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/search/short", method = {RequestMethod.GET})
    public QResultDto getCustomerShort(@RequestParam(defaultValue = "") String q,
                                  @RequestParam(defaultValue = "code") String sortName,
                                  @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                  @RequestParam(defaultValue = "1") int pageIndex,
                                  @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                  @RequestParam(name = "userType", defaultValue = "1") int userType) throws BizException {

        q = StringUtils.replaceSqlPattern(q);

        return customerService.findShort(q, sortName, isAsc, pageIndex, pageSize, userType);
    }

    /**
     * 商品添加企业限制客户列表,返回id， userName, code
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "商品添加企业限制客户列表", notes = "商品添加企业限制客户列表，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字,账户名称或公司名称",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "supplierCode", value = "供应商code",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "客户类型：1是物流，2是贸易， 3两者都是",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/search/short/goods", method = {RequestMethod.GET})
    public QResultDto getCustomerShortForGoods(@RequestParam(defaultValue = "") String q,
                                       @RequestParam(defaultValue = "") String supplierCode,
                                       @RequestParam(defaultValue = "") String sortName,
                                       @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                       @RequestParam(defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                       @RequestParam(name = "userType", defaultValue = "1") int userType) throws BizException {

        q = StringUtils.replaceSqlPattern(q);

        return customerService.findShortForGoods(q, supplierCode, sortName, isAsc, pageIndex, pageSize, userType);
    }


    /**
     * 锁定客户 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "锁定客户", notes = "不允许登录<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/lock", method = {RequestMethod.POST})
    public ResultDto lockCustomer(@ApiParam(value = "客户的ids", required = true) @RequestBody List<Integer> ids)
            throws Exception {

        customerService.lockCustomer(ids);

        ResultDto dto = getOperateSuccessDto(MessagesCodes.CUSTOMER_LOCK_SUCCESS);

        dto.setData(ids);

        return dto;
    }

    /**
     * 解锁客户子账户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "解锁定客户", notes = "允许登录<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/unlock", method = {RequestMethod.POST})
    public ResultDto unLockCustomer(@RequestBody List<Integer> ids) throws Exception {
        customerService.unlockCustomer(ids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.CUSTOMER_UNLOCK_SUCCESS);
        dto.setData(ids);
        return dto;
    }

    /**
     * 新建一个客户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "新建客户", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public ResultDto saveCustomer(@RequestBody @Validated CusCustomer cusCustomer) throws Exception {

        int id = customerService.save(cusCustomer);
        CusCustomer cusCustomerResult = customerService.findSimpleById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("creator", cusCustomerResult.getCreator());
        result.put("createTime", cusCustomerResult.getCreateTime());
        result.put("id", cusCustomerResult.getId());
        ResultDto dto = getOperateSuccessDto(MessagesCodes.MODULE_CUSTOMER_ADD_MAINACCOUNT_SUCCESS);
        dto.setData(result);
        return dto;
    }

    /**
     * 修改一个客户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "修改客户", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "", method = {RequestMethod.PUT})
    public ResultDto updateCustomer(@RequestBody @Validated CusCustomer cusCustomer) throws Exception {

        List<CusCustomer> cusCustomerList = new ArrayList<CusCustomer>();

        cusCustomerList.add(cusCustomer);

        customerService.update(cusCustomerList);

        ResultDto dto = getUpdateSuccessDto(MessagesCodes.MODULE_CUSTOMER_MAINACCOUNT);

        dto.setData(cusCustomer.getId());

        return dto;
    }

    /**
     * 批量删除客户 非物理删除 打标志 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "批量删除客户", notes = "非物理删除 打标志 不允许登录<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "客户的ids",
                    required = true, dataType = "string", paramType = "body")})
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    public ResultDto deleteCustomer(@RequestBody List<Integer> ids) throws Exception {

        customerService.batchDelete(ids);

        return getDeleteSuccessDto(MessagesCodes.MODULE_CUSTOMER_MAINACCOUNT);
    }

    /**
     * 凭借主账号Id查询主账号信息
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "凭借主账号Id查询主账号信息", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public QResultDto findCustomerByCustomerId(@PathVariable int id) throws Exception {

        CusCustomerDto cusCustomerDto = customerService.findById(id);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(cusCustomerDto);

        return qResultDto;
    }

    /**
     * 检查code是否已经存在
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "检查code是否已经存在", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    public QResultDto checkCodeExist(@RequestParam String code) throws Exception {

        Boolean isExist = customerService.checkCodeExist(code);

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(isExist);

        return qResultDto;
    }

    /**
     * 检查email是否已经存在
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "检查email是否已经存在", notes = "-<br>权限：" +
            Permissions.CUSTOMER_LOGISTICS_MGT + " or " +Permissions.CUSTOMER_TRADE_MGT)
    @RequiresPermissions(value = {Permissions.CUSTOMER_LOGISTICS_MGT,Permissions.CUSTOMER_TRADE_MGT},
            logical = Logical.OR)
    @RequestMapping(value = "/email", method = {RequestMethod.POST})
    public QResultDto checkEmailExist(@RequestBody Map<String, String> email) throws Exception {

        Boolean isExist = customerService.checkEmailExist(email.get("email"));
        if (isExist == false) {
            isExist = customerUserService.customerEmailExist(0, email.get("email"));
        }
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(isExist);
        return qResultDto;
    }

    /**
     * 下拉框获取物流用户列表
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "下拉框获取物流用户列表接口专用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字,username或code",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/logistics/list", method = {RequestMethod.GET})
    public QResultDto findNameCodeDtoForLogistic(@RequestParam(defaultValue = "") String q,
                                      @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize)
            throws Exception {


        q = StringUtils.replaceSqlPattern(q);

        return customerService.findNameCodeDtoForLogistic(q,pageIndex,pageSize);
    }

    /**
     * 下拉框获取贸易用户列表
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "下拉框获取贸易用户列表接口专用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字,username或code",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/trade/list", method = {RequestMethod.GET})
    public QResultDto findNameCodeDtoForTrade(@RequestParam(defaultValue = "") String q,
                                              @RequestParam(defaultValue = "1") int pageIndex,
                                              @RequestParam(name = "pageSize", defaultValue = "10") int pageSize)
            throws Exception {


        q = StringUtils.replaceSqlPattern(q);

        return customerService.findNameCodeDtoForTrade(q,pageIndex,pageSize);
    }
}
